// 企业产品页面
import { getEnterprisePublishList } from '../../../api/publish.js';
import { 
  PAGE_PRODUCT_DETAIL, 
  PAGE_BULK_MATERIAL_DETAIL, 
  PAGE_DEMAND_DETAIL,
  PAGE_GROUP_DETAIL,
  goToPage 
} from '../../../config/pages.js';
import { formatDate } from '../../../utils/time';
import { formatSpecification } from '../../../utils/util';

interface ProductItem {
  id: string;
  product_name: string;
  category_name: string;
  description: string;
  status: number; // 0: 下架, 1: 上架, 2: 待审核
  created_at: string;
  view_count?: number;
  enterprise_id: string;
  enterprise_name: string;
}

Page({
  data: {
    // 企业信息
    enterpriseId: '',
    enterpriseName: '',
    
    // 产品列表
    productList: [] as ProductItem[],
    
    // 搜索相关
    searchKeyword: '',
    
    // 分页相关
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    
    // 状态
    refreshing: false,
  },

  onLoad(options: any) {
    console.log('企业产品页面加载参数:', options);
    
    // 获取企业ID和企业名称
    const enterpriseId = options.enterpriseId || options.id;
    const enterpriseName = options.enterpriseName || options.name || '企业产品';
    
    if (!enterpriseId) {
      wx.showToast({
        title: '企业ID不能为空',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    // 解码URL编码的企业名称
    const decodedEnterpriseName = decodeURIComponent(enterpriseName);
    
    this.setData({
      enterpriseId,
      enterpriseName: decodedEnterpriseName
    });
    
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: decodedEnterpriseName + ' - 产品'
    });
    
    // 加载产品列表
    this.loadProductList(true);
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.enterpriseId) {
      this.refreshProductList();
    }
  },

  onPullDownRefresh() {
    this.refreshProductList();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreProducts();
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 加载产品列表
  async loadProductList(isRefresh = false) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      const page = isRefresh ? 1 : this.data.currentPage;
      const params: any = {
        enterprise_id: this.data.enterpriseId,
        page,
        limit: this.data.pageSize
      };
      
      // 只有当搜索关键词存在且不为空时才添加keyword参数
      if (this.data.searchKeyword && this.data.searchKeyword.trim()) {
        params.keyword = this.data.searchKeyword.trim();
      }
      
      console.log('加载产品列表参数:', params);
      
      const response = await getEnterprisePublishList(params);
      console.log('产品列表响应:', response);
      
      if (response.status === 200 && response.data) {
        const { list, count } = response.data;
        
        let newProductList = list || [];
        
        // 处理产品数据格式
        newProductList = newProductList.map((item: any) => ({
          ...item,
          spec: formatSpecification(item.spec || ''), // 格式化规格
          formatted_date: formatDate(item.add_time || item.create_time),
          // 添加类型信息
          typeName: this.getTypeName(item.type),
          typeClass: this.getTypeClass(item.type)
        }));
        
        if (isRefresh) {
          this.setData({
            productList: newProductList,
            currentPage: 1,
            hasMore: newProductList.length < (count || 0)
          });
        } else {
          this.setData({
            productList: [...this.data.productList, ...newProductList],
            currentPage: page + 1,
            hasMore: this.data.productList.length + newProductList.length < (count || 0)
          });
        }
        
        console.log('产品列表更新成功:', this.data.productList.length);
      } else {
        throw new Error(response.message || '获取产品列表失败');
      }
    } catch (error: any) {
      console.error('加载产品列表失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
      if (isRefresh) {
        wx.stopPullDownRefresh();
      }
    }
  },

  // 刷新产品列表
  refreshProductList() {
    this.setData({ refreshing: true });
    this.loadProductList(true).finally(() => {
      this.setData({ refreshing: false });
    });
  },

  // 加载更多产品
  loadMoreProducts() {
    this.loadProductList(false);
  },

  // 搜索相关
  onSearchSubmit(e: any) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword,
      currentPage: 1,
      hasMore: true
    });
    this.loadProductList(true);
  },

  onSearchClear() {
    this.setData({
      searchKeyword: '',
      currentPage: 1,
      hasMore: true
    });
    this.loadProductList(true);
  },

  // 跳转到详情页（与search-results保持一致）
  goToDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    
    console.log('跳转到详情页:', { id, type });
    
    let pagePath = '';
    switch (type) {
      case 'group':
        pagePath = PAGE_GROUP_DETAIL;
        break;
      case 'demand':
        pagePath = PAGE_DEMAND_DETAIL;
        break;
      case 'processing':
        pagePath = PAGE_PRODUCT_DETAIL;
        break;
      case 'material':
        pagePath = PAGE_PRODUCT_DETAIL;
        break;
      case 'inventory':
        pagePath = PAGE_BULK_MATERIAL_DETAIL;
        break;
      default:
        pagePath = PAGE_PRODUCT_DETAIL;
    }
    
    goToPage(pagePath, { id });
  },



  // 获取类型名称
  getTypeName(type: string): string {
    const typeMap: any = {
      'group': '拼单',
      'demand': '求购',
      'processing': '加工',
      'material': '材料',
      'inventory': '散料'
    };
    return typeMap[type] || type;
  },

  // 获取类型样式类名
  getTypeClass(type: string): string {
    const classMap: any = {
      'group': 'group-order-item',
      'demand': 'demand-item',
      'processing': 'process-item',
      'material': 'material-item',
      'inventory': 'bulk-material-item'
    };
    return classMap[type] || 'material-item';
  },

});
